<template>
	<view>
		<u-navbar :placeholder="true" :safeAreaInsetTop="true" @leftClick="back" title="注册"></u-navbar>
		<view class="main">
			<uni-title type="h1" title="应聘者注册"></uni-title>
			<up-form labelWidth="80" labelPosition="left" :model="model1" :rules="rules" ref="form1">
				<!-- 表单项 -->
				<up-divider></up-divider>
				<up-form-item label="姓名" prop="userInfo.name" borderBottom ref="form1">
					<up-input placeholder="请输入姓名" v-model="model1.userInfo.name" border="none"></up-input>
					<up-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="1" width="60" height="60"></up-upload>
				</up-form-item>
				<up-divider></up-divider>
				<up-form-item label="手机号" prop="userInfo.account" borderBottom ref="form1">
					<up-input placeholder="请输入手机号" v-model="model1.userInfo.account" border="none"></up-input>
				</up-form-item>
				<up-divider></up-divider>
				<up-form-item label="密码" prop="userInfo.password" borderBottom ref="form1">
					<up-input placeholder="请输入密码" password v-model="model1.userInfo.password" border="none"></up-input>
				</up-form-item>
				<up-divider></up-divider>
				<up-form-item label="确认密码" prop="userInfo.repeatPassword" borderBottom ref="form1">
					<up-input placeholder="请再次确认密码" password v-model="model1.userInfo.repeatPassword" border="none"></up-input>
				</up-form-item>
				<up-divider></up-divider>
				<up-form-item label="性别" prop="userInfo.sex" borderBottom @click="showSex = true" ref="item1">
					<up-input
						@click="showSex = true"
						style="width: 200px"
						v-model="model1.userInfo.sex"
						disabled
						disabledColor="#ffffff"
						placeholder="请选择性别"
						border="none"
					></up-input>
					<template #right>
						<up-icon name="arrow-right"></up-icon>
					</template>
					<up-action-sheet
						:show="showSex"
						:actions="actions"
						title="请选择性别"
						description="如果选择保密会报错"
						@close="showSex = false"
						@select="sexSelect"
					></up-action-sheet>
				</up-form-item>
				<up-divider></up-divider>
				<up-form-item label="身份证" prop="userInfo.idCard" borderBottom ref="form1">
					<up-input placeholder="请输入身份证" v-model="model1.userInfo.idCard" border="none"></up-input>
				</up-form-item>
				<up-divider></up-divider>
				<u-form-item label="年龄" prop="userInfo.age" borderBottom ref="form1" @click="show = true">
					<up-input @click="show = true" v-model="model1.userInfo.age" disabled disabledColor="#ffffff" placeholder="请选择出生日期" border="none"></up-input>
					<template #right>
						<up-icon name="arrow-right"></up-icon>
					</template>
					<up-datetime-picker
						title="请选择出生日期"
						v-model="birthDate"
						:show="show"
						ref="datetimePicker"
						@confirm="calculateAge"
						@cancel="show = false"
						mode="date"
						:minDate="0"
						:maxDate="Number(new Date())"
						:formatter="formatter"
					></up-datetime-picker>
				</u-form-item>
				<up-divider></up-divider>
				<up-form-item label="邮箱" prop="userInfo.email" borderBottom ref="form1">
					<up-input placeholder="请输入邮箱" v-model="model1.userInfo.email" border="none"></up-input>
				</up-form-item>
				<up-divider></up-divider>
				<up-form-item label="学历" prop="userInfo.education" borderBottom ref="form1" @click="actionSheetVisible = true">
					<up-input
						@click="actionSheetVisible = true"
						v-model="model1.userInfo.education"
						disabled
						disabledColor="#ffffff"
						placeholder="请选择学历"
						border="none"
					></up-input>
					<template #right>
						<up-icon name="arrow-right"></up-icon>
					</template>
					<up-action-sheet
						title="请选择学历"
						:show="actionSheetVisible"
						:actions="educationOptions"
						@select="onSelectEducation"
						@close="actionSheetVisible = false"
					></up-action-sheet>
				</up-form-item>
				<up-divider></up-divider>
				<up-form-item label="地址" prop="userInfo.address" borderBottom ref="form1" @click="value = true">
					<up-input @click="value = true" v-model="model1.userInfo.address" disabled disabledColor="#ffffff" placeholder="请选择地址" border="none"></up-input>
					<template #right>
						<up-icon name="arrow-right"></up-icon>
					</template>
					<city-select v-model="value" @city-change="cityChange"></city-select>
				</up-form-item>
				<up-divider></up-divider>
				<up-form-item label="毕业院校" prop="userInfo.school" borderBottom ref="form1">
					<up-input placeholder="请输入毕业院校" v-model="model1.userInfo.school" border="none"></up-input>
				</up-form-item>
				<up-divider></up-divider>
			</up-form>
		</view>
		<view class="register">
			<view>
				<u-checkbox-group class="agreement" v-model="radiovalue">
					<up-checkbox shape="square" label="已阅读并同意" name="test"></up-checkbox>
					<text style="color: dodgerblue">《招聘软件许可及服务协议》</text>
				</u-checkbox-group>
			</view>
			<up-button type="primary" size="large" text="注册" @click="submitForm"></up-button>
		</view>
		<view class="safe-area"></view>
	</view>
</template>

<script>
import citySelect from '@/common/u-city-select.vue';
export default {
	components: {
		citySelect
	},
	data() {
		return {
			// 用户信息
			model1: {
				userInfo: {
					account: '',
					name: '',
					password: '',
					repeatPassword: '',
					candidateImg: '',
					sex: '',
					idCard: '',
					age: '',
					email: '',
					education: '',
					address: '',
					identity: '社会人',
					school: '',
					recommendedStatus: '无',
					wallet: 0,
					status: '启用'
				}
			},
			// 表单验证
			rules: {
				'userInfo.name': [{ required: true, message: '请输入姓名', trigger: 'blur' }],
				'userInfo.phone': [
					{ required: true, message: '请输入手机号', trigger: 'blur' },
					{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
				],
				'userInfo.password': [
					{ required: true, message: '请输入密码', trigger: 'blur' },
					{ min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
				],
				'userInfo.repeatPassword': [
					{ required: true, message: '请再次确认密码', trigger: 'blur' },
					{
						validator: (rule, value, callback) => {
							if (value !== this.model1.userInfo.password) {
								callback(new Error('两次输入的密码不一致'));
							} else {
								callback();
							}
						},
						trigger: 'blur'
					}
				],
				'userInfo.sex': [{ required: true, message: '请选择性别', trigger: 'blur' }],
				'userInfo.idCard': [
					{ required: true, message: '请输入身份证', trigger: 'blur' },
					{ pattern: /^\d{15}|\d{18}$/, message: '请输入有效的身份证号', trigger: 'blur' }
				],
				'userInfo.email': [
					{ required: true, message: '请输入邮箱', trigger: 'blur' },
					{ type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
				],
				'userInfo.education': [{ required: true, message: '请选择学历', trigger: 'blur' }],
				'userInfo.address': [{ required: true, message: '请选择地址', trigger: 'blur' }],
				'userInfo.school': [{ required: true, message: '请输入毕业院校', trigger: 'blur' }]
			},
			fileList: [], // 文件列表
			// 性别
			actions: [
				{
					name: '男'
				},
				{
					name: '女'
				},
				{
					name: '保密'
				}
			],
			showSex: false, // 性别显示
			birthDate: Number(new Date()), // 出生日期
			show: false, // 日期显示
			actionSheetVisible: false, // 学历显示
			// 学历
			educationOptions: [
				{ name: '高中', value: '高中' },
				{ name: '大专', value: '大专' },
				{ name: '本科', value: '本科' },
				{ name: '硕士', value: '硕士' },
				{ name: '博士', value: '博士' }
			],
			height: 30, // 城市选择高度
			bgColor: this.$u.color.bgColor, // 背景颜色
			marginTop: 30, // 顶部间隔
			marginBottom: 30, // 底部间隔
			value: false, // 城市选择显示
			radiovalue: [] // 复选框选中
		};
	},
	onReady() {
		// 微信小程序需要用此写法
		this.$refs.datetimePicker.setFormatter(this.formatter);
	},
	methods: {
		// 返回上一页（有bug，点击会变成刷新页面）
		back() {
			event.preventDefault();
			uni.navigateBack({
				delta: 1
			});
		},
		// 删除图片
		deletePic(event) {
			console.log(this.fileList);
			this.fileList.splice(event.index, 1);
		},
		// 新增图片
		async afterRead(event) {
			let lists = [].concat(event.file);
			let fileListLen = this.fileList.length;
			lists.map((item) => {
				this.fileList.push({
					...item,
					status: 'uploading',
					message: '上传中'
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url);
				let item = this.fileList[fileListLen];
				this.fileList.splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					})
				);
				fileListLen++;
			}
		},
		// 上传图片
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: 'api/recruit-fileUpload/files/upload',
					filePath: url,
					name: 'file',
					formData: {
						user: 'test'
					},
					success: (res) => {
						if (res.statusCode === 200) {
							resolve(res.data);
							this.model1.userInfo.candidateImg = res.data.relativePath;
						} else {
							reject(`上传失败，状态码：${res.statusCode}`);
						}
					},
					fail: (err) => {
						reject(`上传失败，错误信息：${err.errMsg}`);
					}
				});
			});
		},
		// 选择性别
		sexSelect(e) {
			this.model1.userInfo.sex = e.name;
			this.$refs.form1.validateField('userInfo.sex');
			this.showSex = false;
		},
		// 计算年龄
		calculateAge(date) {
			const birthDate = new Date(date.value);
			const today = new Date();
			let age = today.getFullYear() - birthDate.getFullYear();
			const monthDiff = today.getMonth() - birthDate.getMonth();
			if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
				age--;
			}
			this.model1.userInfo.age = age;
			this.show = false;
		},
		// 格式化日期
		formatter(type, value) {
			if (type === 'year') {
				return `${value}年`;
			}
			if (type === 'month') {
				return `${value}月`;
			}
			if (type === 'day') {
				return `${value}日`;
			}
			return value;
		},
		// 显示学历组件
		showActionSheet() {
			this.actionSheetVisible = true;
		},
		// 选择学历
		onSelectEducation(option) {
			this.model1.userInfo.education = option.value;
			this.actionSheetVisible = false;
		},
		// 选择地址
		cityChange(e) {
			this.model1.userInfo.address = e.province.label + '-' + e.city.label + '-' + e.area.label;
		},
		// 注册
		submitForm() {
			if (this.radiovalue.length === 0) {
				uni.showToast({
					title: '请先阅读并同意软件协议',
					icon: 'none'
				});
				return;
			}
			this.$refs.form1
				.validate()
				.then((res) => {
					console.log('表单验证通过');
					this.$api.register(this.model1.userInfo).then((res) => {
						uni.showToast({
							title: `${res.code === 200 ? '注册成功' : '注册失败'}`,
							icon: 'none'
						});
						uni.redirectTo({
							url: '/pages/index/login'
						});
					});
				})
				.catch((error) => {
					console.log('表单验证失败');
					return false;
				});
		}
	}
};
</script>

<style>
.main {
	margin-left: 20px;
	margin-right: 20px;
	padding-bottom: env(safe-area-inset-bottom);
}
.u-divider[data-v-ea022cee] {
	margin: 0;
}
.uni-input-wrapper {
	width: 180px;
}
.u-upload[data-v-c8491d64] {
	margin-right: -60%;
}
.register {
	position: fixed;
	bottom: 0;
	width: 95%;
	background-color: #fff;
	padding: 10px;
	box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
}

.agreement {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 10px;
}

.safe-area {
	padding-bottom: calc(env(safe-area-inset-bottom) + 130px);
}
</style>
